package com.arguigu.gmall.order.controller;

import com.arguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**订单管理
 * @author Administrator
 * @create 2020-05-27 19:32
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    //生成订单号
    @GetMapping("/auth/tradeNo")
    public String tradeNo(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //订单号在缓存中的值
        String tradeNoKey = "user:" + userId + ":tradeCode";
        String tradeNo = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(tradeNoKey,tradeNo);
        return tradeNo;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, String tradeNo, HttpServletRequest request){
        //一：判读订单号的正确性
        String userId = AuthContextHolder.getUserId(request);
        String tradeNoKey = "user:"+userId+":tradeCode";
        //1）.判断传过来的订单号是否为空
        if(StringUtils.isEmpty(tradeNo)){
            return Result.fail().message("非法操作");
        }
        //2）.不为空去查询缓存
        String key1 = (String)redisTemplate.opsForValue().get(tradeNoKey);
        //3).订单提交后会删除，判断它是否为空
        if(StringUtils.isEmpty(key1)){
            return Result.fail().message("请不要重复提交订单");
        }else {
            //4).如果说两个订单号不相等，非法操作
            if(!key1.equals(tradeNo)){
                return Result.fail().message("非法操作");
            }
        }
        //二：正确，提交订单
        //2.1)校验库存（已经没有库存）
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for(OrderDetail orderDetail:orderDetailList){
            boolean hasStock = orderInfoService.hasStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
            if(!hasStock){
                return Result.fail().message(orderDetail.getSkuName() + ":库存不足");
            }
        }
        //2.2)保存订单
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.submitOrder(orderInfo);
        return Result.ok(orderId);
    }

    //对外暴露订单对象
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable(name = "orderId") Long orderId){
        return orderInfoService.getOrderInfo(orderId);
    }

    //由库存微服务发送请求：要求拆分订单
    @PostMapping("/orderSplit")
    public List<Map<String,Object>> orderSplit(String orderId,String wareSkuMap){
        //1.拆分订单
        List<OrderInfo> orderInfoList = orderInfoService.orderSplit(orderId, wareSkuMap);
        //2.返回值 List<Map<String, Object>>
        List<Map<String, Object>> mapList = orderInfoList.stream().map(orderInfo -> {
            return orderInfoService.initWareOrder(orderInfo);
        }).collect(Collectors.toList());
        return mapList;

    }
}
